<template>
  <div class="notifications-container">
    <h1 class="page-title">通知中心</h1>
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    <div v-else-if="error" class="error-container">
      <el-alert
        :title="error"
        type="error"
        show-icon
      />
    </div>
    <div v-else class="notifications-content">
      <div class="filter-container">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="状态">
            <el-select v-model="filterForm.status" placeholder="通知状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="未读" value="unread" />
              <el-option label="已读" value="read" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="类型">
            <el-select v-model="filterForm.type" placeholder="通知类型" clearable>
              <el-option label="全部" value="" />
              <el-option label="系统通知" value="system" />
              <el-option label="任务提醒" value="task" />
              <el-option label="文件变更" value="file" />
              <el-option label="用户提及" value="mention" />
              <el-option label="评论回复" value="comment" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="searchNotifications">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
            <el-button 
              type="info" 
              :disabled="!hasUnread" 
              @click="markAllAsRead"
            >
              全部标为已读
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div v-if="filteredNotifications.length === 0" class="empty-notifications">
        <el-empty description="没有通知" />
      </div>
      
      <div v-else class="notifications-list">
        <div v-for="(group, date) in groupedNotifications" :key="date" class="notification-group">
          <div class="date-header">{{ formatDate(date) }}</div>
          
          <el-card 
            v-for="notification in group" 
            :key="notification.id"
            :class="['notification-card', { 'unread': !notification.read_at }]"
            shadow="hover"
            @click="openNotification(notification)"
          >
            <div class="notification-icon">
              <el-icon v-if="notification.type === 'system'"><Bell /></el-icon>
              <el-icon v-else-if="notification.type === 'task'"><Calendar /></el-icon>
              <el-icon v-else-if="notification.type === 'file'"><Document /></el-icon>
              <el-icon v-else-if="notification.type === 'mention'"><User /></el-icon>
              <el-icon v-else-if="notification.type === 'comment'"><ChatLineRound /></el-icon>
              <el-icon v-else><InfoFilled /></el-icon>
            </div>
            
            <div class="notification-content">
              <div class="notification-title">{{ notification.title }}</div>
              <div class="notification-message">{{ notification.message }}</div>
              <div class="notification-meta">
                <span class="time">{{ formatTime(notification.created_at) }}</span>
                <el-tag 
                  :type="getNotificationTypeTag(notification.type)" 
                  size="small"
                >
                  {{ getNotificationTypeLabel(notification.type) }}
                </el-tag>
                <el-tag 
                  v-if="!notification.read_at" 
                  type="danger" 
                  size="small"
                >
                  未读
                </el-tag>
              </div>
            </div>
            
            <div class="notification-actions">
              <el-button 
                v-if="!notification.read_at"
                size="small" 
                type="primary" 
                @click.stop="markAsRead(notification.id)"
              >
                标为已读
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click.stop="deleteNotification(notification.id)"
              >
                删除
              </el-button>
            </div>
          </el-card>
        </div>
      </div>
      
      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="totalNotifications"
          layout="total, prev, pager, next, jumper"
          @current-change="handlePageChange"
        />
      </div>
    </div>
    
    <!-- 确认删除对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
    >
      <span>确定要删除这条通知吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Bell, Calendar, Document, User, ChatLineRound, InfoFilled } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'Notifications',
  components: {
    Bell,
    Calendar,
    Document,
    User,
    ChatLineRound,
    InfoFilled
  },
  setup() {
    const router = useRouter()
    const notifications = ref([])
    const loading = ref(true)
    const error = ref('')
    const totalNotifications = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const deleteDialogVisible = ref(false)
    const notificationToDelete = ref(null)
    const filterForm = reactive({
      status: '',
      type: '',
      dateRange: []
    })
    
    const fetchNotifications = async () => {
      loading.value = true
      error.value = ''
      
      try {
        const response = await axios.get('/api/notifications', {
          params: {
            page: currentPage.value,
            per_page: pageSize.value
          }
        })
        
        notifications.value = response.data.notifications
        totalNotifications.value = response.data.total
      } catch (err) {
        console.error('获取通知失败:', err)
        error.value = '获取通知列表失败，请稍后重试'
      } finally {
        loading.value = false
      }
    }
    
    const searchNotifications = () => {
      currentPage.value = 1
      fetchNotifications()
    }
    
    const resetFilter = () => {
      filterForm.status = ''
      filterForm.type = ''
      filterForm.dateRange = []
      searchNotifications()
    }
    
    const handlePageChange = (page) => {
      currentPage.value = page
      fetchNotifications()
    }
    
    const openNotification = (notification) => {
      if (!notification.read_at) {
        markAsRead(notification.id)
      }
      
      if (notification.link) {
        router.push(notification.link)
      }
    }
    
    const markAsRead = async (notificationId) => {
      try {
        await axios.put(`/api/notifications/${notificationId}/read`)
        
        const notification = notifications.value.find(n => n.id === notificationId)
        if (notification) {
          notification.read_at = new Date().toISOString()
        }
        
        ElMessage.success('已标记为已读')
      } catch (err) {
        console.error('标记通知已读失败:', err)
        ElMessage.error('操作失败，请稍后重试')
      }
    }
    
    const markAllAsRead = async () => {
      try {
        await axios.put('/api/notifications/read-all')
        
        notifications.value.forEach(notification => {
          if (!notification.read_at) {
            notification.read_at = new Date().toISOString()
          }
        })
        
        ElMessage.success('已将所有通知标记为已读')
      } catch (err) {
        console.error('标记所有通知已读失败:', err)
        ElMessage.error('操作失败，请稍后重试')
      }
    }
    
    const deleteNotification = (notificationId) => {
      notificationToDelete.value = notificationId
      deleteDialogVisible.value = true
    }
    
    const confirmDelete = async () => {
      if (!notificationToDelete.value) return
      
      try {
        await axios.delete(`/api/notifications/${notificationToDelete.value}`)
        
        notifications.value = notifications.value.filter(
          n => n.id !== notificationToDelete.value
        )
        totalNotifications.value--
        
        ElMessage.success('通知已删除')
        deleteDialogVisible.value = false
      } catch (err) {
        console.error('删除通知失败:', err)
        ElMessage.error('删除失败，请稍后重试')
      }
    }
    
    const formatDate = (dateString) => {
      const date = new Date(dateString)
      const today = new Date()
      const yesterday = new Date(today)
      yesterday.setDate(yesterday.getDate() - 1)
      
      if (date.toDateString() === today.toDateString()) {
        return '今天'
      } else if (date.toDateString() === yesterday.toDateString()) {
        return '昨天'
      } else {
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: 'long',
          day: 'numeric'
        })
      }
    }
    
    const formatTime = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    const getNotificationTypeLabel = (type) => {
      const typeMap = {
        'system': '系统通知',
        'task': '任务提醒',
        'file': '文件变更',
        'mention': '用户提及',
        'comment': '评论回复'
      }
      
      return typeMap[type] || '其他通知'
    }
    
    const getNotificationTypeTag = (type) => {
      const typeTagMap = {
        'system': 'info',
        'task': 'warning',
        'file': 'success',
        'mention': 'danger',
        'comment': 'primary'
      }
      
      return typeTagMap[type] || ''
    }
    
    const filteredNotifications = computed(() => {
      let result = [...notifications.value]
      
      if (filterForm.status === 'read') {
        result = result.filter(n => n.read_at)
      } else if (filterForm.status === 'unread') {
        result = result.filter(n => !n.read_at)
      }
      
      if (filterForm.type) {
        result = result.filter(n => n.type === filterForm.type)
      }
      
      if (filterForm.dateRange && filterForm.dateRange.length === 2) {
        const startDate = new Date(filterForm.dateRange[0])
        const endDate = new Date(filterForm.dateRange[1])
        endDate.setHours(23, 59, 59, 999)
        
        result = result.filter(n => {
          const notificationDate = new Date(n.created_at)
          return notificationDate >= startDate && notificationDate <= endDate
        })
      }
      
      return result
    })
    
    const groupedNotifications = computed(() => {
      const groups = {}
      
      filteredNotifications.value.forEach(notification => {
        const date = notification.created_at.split('T')[0]
        if (!groups[date]) {
          groups[date] = []
        }
        groups[date].push(notification)
      })
      
      return Object.fromEntries(
        Object.entries(groups).sort((a, b) => {
          return new Date(b[0]) - new Date(a[0])
        })
      )
    })
    
    const hasUnread = computed(() => {
      return notifications.value.some(n => !n.read_at)
    })
    
    onMounted(() => {
      fetchNotifications()
    })
    
    return {
      notifications,
      loading,
      error,
      totalNotifications,
      currentPage,
      pageSize,
      deleteDialogVisible,
      notificationToDelete,
      filterForm,
      filteredNotifications,
      groupedNotifications,
      hasUnread,
      searchNotifications,
      resetFilter,
      handlePageChange,
      openNotification,
      markAsRead,
      markAllAsRead,
      deleteNotification,
      confirmDelete,
      formatDate,
      formatTime,
      getNotificationTypeLabel,
      getNotificationTypeTag
    }
  }
}
</script>

<style scoped>
.notifications-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
}

.loading-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.notifications-list {
  background: #f5f7fa;
  border-radius: 4px;
  min-height: 300px;
}

.notification-groups {
  padding: 10px;
}

.notification-group {
  margin-bottom: 20px;
}

.date-header {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}

.notification-card {
  margin-bottom: 10px;
  display: flex;
  align-items: flex-start;
  cursor: pointer;
  transition: all 0.3s;
}

.notification-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.notification-card.unread {
  background-color: #ecf5ff;
  border-left: 3px solid #409EFF;
}

.notification-icon {
  margin-right: 15px;
  font-size: 24px;
  color: #409EFF;
}

.notification-content {
  flex: 1;
}

.notification-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #303133;
}

.notification-message {
  color: #606266;
  margin-bottom: 8px;
  line-height: 1.5;
}

.notification-meta {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 12px;
}

.notification-meta .time {
  margin-right: 10px;
}

.notification-meta .el-tag {
  margin-right: 5px;
}

.notification-actions {
  margin-left: 15px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.empty-notifications {
  margin: 40px 0;
  text-align: center;
}
</style> 